<template>
  <div>
    <el-form label-width="60px" :rules="rules" :model="account" ref="formRef">
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, defineExpose } from 'vue'
import { useStore } from 'vuex'

import { rules } from '../config/accountConfig'
import { ElForm } from 'element-plus'
import cache from '@/utils/cache'

const store = useStore()

const account = reactive({
  name: cache.get('name') ?? '',
  password: cache.get('password') ?? ''
})

const formRef = ref<InstanceType<typeof ElForm>>()
const loginAction = (isKeepPassword: boolean) => {
  formRef.value?.validate((valid) => {
    if (valid) {
      if (isKeepPassword) {
        cache.set('name', account.name)
        cache.set('password', account.password)
      } else {
        cache.delete('name')
        cache.delete('password')
      }

      store.dispatch('login/accountLoginAction', { ...account })
    }
  })
}

defineExpose({
  loginAction
})
</script>

<style scoped lang="less"></style>
